package top.hkyzf.study.leetcode.linkedlist;

import org.junit.Test;

import java.util.Random;

/**
 * 链表随机节点
 * @author 朱峰
 * @date 2022-1-16 1:02
 */
public class 链表随机节点_382 {

    static class Solution {
        ListNode head;
        Random random;

        public Solution(ListNode head) {
            this.head = head;
            this.random = new Random();
        }

        public int getRandom() {
            int result = 0;
            int index = 1;
            ListNode node = head;
            while (node != null) {
                if(random.nextInt(index) == 0) {
                    result = node.val;
                }
                node = node.next;
                index++;
            }
            return result;
        }
    }

    @Test
    public void testGetRandom () {
        ListNode node2 = new ListNode(3);
        ListNode node1 = new ListNode(2, node2);
        ListNode head = new ListNode(1, node1);
        Solution randomNode = new Solution(head);
        System.out.println(randomNode.getRandom());
        System.out.println(randomNode.getRandom());
        System.out.println(randomNode.getRandom());
    }
}
